<?php
/**
 * Created by PhpStorm.
 * User: 三星
 * Date: 2018/4/13
 * Time: 22:14
 */

namespace User\Controller;

use Common\Controller\MemberbaseController;

class InfoController extends MemberbaseController
{
    private function input_csv($handle)
    {
        $out = array ();
        $n = 0;
        while ($data = fgetcsv($handle, 10000))
        {
            $num = count($data);
            for ($i = 0; $i < $num; $i++)
            {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }
        return $out;
    }

    public function exportall(){
        //需要判断用户身份才可以进行导出数据
        if($this->user['id'] == 207 || $this->user['id'] == 210 ){

        }else{
            $this->error("你没有此权限");
        }

        $begintime = I('begintime');
        $endtime = I('endtime');
        $finalmap = array("status"=>1);
        $filename = '用户列表_' . date('YmdHis') . '.csv';
        //由于导出数据增加，改为拼接查询语句
        $seldata = array();
        if($begintime && $endtime){
            $map['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
            $map['lastcosttime'] = array(array('gt', $begintime), array('lt', $endtime));
            $map['_logic'] = 'or';
            //放在外面也会拼接，就会多出来一个and报错了
            $finalmap['_complex'] = $map;
            $seldata['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
        }
        //设置不访问超时
        set_time_limit(0);
        $now = gmdate("D, d M Y H:i:s");

        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");
        $lists =D('userinfo')->relation(true)->where($finalmap)->order('createtime desc')->select();

        $datas = array();
        foreach ($lists as $k => $v){
            //遍历的同时查出当月的账目变动
            //扣费金额
            $seldata['storetype'] = 2;
            $seldata['cardnum'] = $v['cardnum'];
            $kf = M('store')->where($seldata)->sum('storemoney');
            $seldata['storetype'] = 1;
            //充值金额
            $cz =  M('store')->where($seldata)->sum('storemoney');
            $data = [
                $lists[$k]['id'],
                $lists[$k]['cardnum'],
                $lists[$k]['name'],
                $lists[$k]['tel'],
                $lists[$k]['address'],
                $lists[$k]['shenfenzheng'],
                $lists[$k]['cardname'],
                $lists[$k]['shengri'],
                $lists[$k]['areaname'],
                $lists[$k]['housename'],
                $lists[$k]['floorname'],
                $lists[$k]['roomname'],
                $lists[$k]['bedname'],
                $lists[$k]['usetime'],
                $lists[$k]['createtime'],
                $lists[$k]['upgradetime'],
                $lists[$k]['extensiontime'],
                $lists[$k]['lastcosttime'],
                $lists[$k]['costcount'],
                $lists[$k]['totalstore']/100,
                $cz/100,
                $kf/100,
                $lists[$k]['totalrentmoney']/100,
                $lists[$k]['remark'],
                $lists[$k]['yewuyuan'],
                $lists[$k]['kaikarenname']
            ];
            $datas[] = $data;
        }
        $head=array('id','卡号','姓名','手机','详细地址','身份证号','级别','生日','地区','楼号','楼层','房间号','床位号','使用期权(月)','合同时间','升级时间','续合同时间','最后消费时间','消费次数','总储值','该时间段内充值金额','该时间段内扣费金额','合计领取','备注','工作人员','开卡人');

        ob_start();

        $df = fopen("php://output", 'w');

        fputcsv($df,$head);
        foreach ($datas as $row) {
            fputcsv($df, $row);
        }
        fclose($df);

        echo ob_get_clean();
        unset($lists);
        unset($datas);
        die();
    }


    public function hisimport(){
        $filename = $_FILES['file']['tmp_name'];
        if(empty ($filename))
        {
            $this->error('请选择要导入的CSV文件！');
            exit;
        }
        $handle = fopen($filename, 'r');
        $result = $this->input_csv($handle); //解析csv
        $len_result = count($result);
        if($len_result==0)
        {
            $this->error('没有任何数据！');
            exit;
        }
        array_shift($result);
        $count = 0;
        foreach ($result as $k => $v){
            if(count($v)>2){//有正常数据

                $cardnum = $v['5'];

                if(!M('userinfo')->where(array('cardnum'=>$cardnum))->find()){
                    continue;
                }
                $storetype = $v['3'];
                if('增加'==$storetype){
                    $storetype = 1;
                }else{
                    $storetype = 2;
                }

               // $nowstore = $v['7']*100;//储值
                $storemoney = $v['9']*100;//实付储值
                $storesendmoney = $v['8']*100;//赠送储值

                $nowstore = $v['10']*100;//当前余额

                $temp[] = array(
                    'cardnum'   => $cardnum,
                    'name'      => $v['6'],
                    'paytype'       => $v['4'],
                    'storemoney' => $storemoney,
                    'storesendmoney'   => $storesendmoney,
                    'createtime'   => $v['12'],
                    'createbyuser'    => $this->user['user_nicename'],
                    'createby'   => $this->user['id'],
                    'storetype'  => $storetype,
                    'nowstore'=> $nowstore,
                   // 'laststore' => $laststore,
                    'remark' => $v['16']

                );

            }
            if(count($temp)>200){
                $count = $count + count($temp);
                D('store')->addAll($temp);
                $temp = array();
            }
        }

        if($temp){
            $count = $count + count($temp);
            D('store')->addAll($temp);
        }

        if($count){
            $this->success('已成功导入'.$count.'条信息！',UU('User/Info/storehis'));
        }else{
            $this->error('未导入任何数据，请确保导入会员卡级别存在，且导入数据在改系统中不存在');
        }
    }


    public function cimport(){
        $filename = $_FILES['file']['tmp_name'];
        if(empty ($filename))
        {
            $this->error('请选择要导入的CSV文件！');
            exit;
        }
        $handle = fopen($filename, 'r');
        $result = $this->input_csv($handle); //解析csv
        $len_result = count($result);
        if($len_result==0)
        {
            $this->error('没有任何数据！');
            exit;
        }

        array_shift($result);

        $count = 0;
        foreach ($result as $k => $v){
            $cardnum = $v['3'];

            $shenfenzheng = $v['25'];

            $sexint = substr($shenfenzheng,16,1);
            $sex = (int)$sexint % 2  ? 1 : 2;

            $temp = array(
                'sex' => $sex,
            );

            if(M('userinfo')->where(array('cardnum'=>$cardnum))->save($temp)){
                $count++;
            }

        }

        if($count){
            $this->success('已成功导入'.$count.'条信息！',UU('User/Info/index'));
        }else{
            $this->error('未导入任何数据，请确保导入会员卡级别存在，且导入数据在改系统中不存在');
        }

    }

    public function cvsimport(){
        $filename = $_FILES['file']['tmp_name'];
        if(empty ($filename))
        {
            $this->error('请选择要导入的CSV文件！');
            exit;
        }
        $handle = fopen($filename, 'r');
        $result = $this->input_csv($handle); //解析csv
        $len_result = count($result);
        if($len_result==0)
        {
            $this->error('没有任何数据！');
            exit;
        }

        array_shift($result);

        $count = 0;
        foreach ($result as $k => $v){
            $cardnum = $v['3'];
            if(M('userinfo')->where(array('cardnum'=>$cardnum))->count()!=0){//存在了不导入
                continue;
            }

            $cardname = $v["6"];
            $card = M('cardlevel')->where(array('cardname'=>$cardname))->find();
            if(!$card){
                continue;
            }

            $totalstore = $v['11']*100;
            $temp[] = array(
                'cardnum'   => $v['3'],
                'name'      => $v['5'],
                'tel'       => $v['9'],
                'cardlevel' => $card['id'],
                'shengri'   => $v['7'],
                'address'   => $v['22'],
                'remark'    => $v['26'],
                'paytype'   => "现金支付",
                'kaikaren'  => $this->user['id'],
               // 'kaikarenname' =>$this->user['user_nicename'],
                'totalstore'=> $totalstore,
                'usedstore' => $totalstore,
                'totalmenoy'=> $totalstore,
                'usedtime'  => $v['19'],
                'createtime'=> $v['14'],
            );

            if(count($temp)>200){
                $count = $count + count($temp);
                D('userinfo')->addAll($temp);
                $temp = array();
            }

        }

        if($temp){
            $count = $count + count($temp);
            D('userinfo')->addAll($temp);
        }

        if($count){
            $this->success('已成功导入'.$count.'条信息！',UU('User/Info/index'));
        }else{
            $this->error('未导入任何数据，请确保导入会员卡级别存在，且导入数据在改系统中不存在');
        }

    }

    public function index(){

        $cardnum = I('cardnum','','trim');

        $cardlevel = I('cardlevel','','trim');

        $tel = I('tel');

        $name = I('name','','trim');

        $status = I('status',1,'int');

        $data = array();
   //     $map = array();
        $condition = array();
//
//        $begintime = I('begintime');
//        $endtime = I('endtime');
//
//        if($begintime && $endtime){
//
//            $map['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
//            $map['lastcosttime'] = array(array('gt', $begintime), array('lt', $endtime));
//            $map['_logic'] = 'or';
//
//        }



        if($cardnum){
            $data['cardnum'] = $cardnum;
            $condition['cardnum'] = $cardnum;
        }

        if($cardlevel){
            $data['cardlevel'] = $cardlevel;
            $condition['cardlevel'] = $cardlevel;
        }

        if($tel){
            $data['tel'] = array('like','%'.$tel.'%');
            $condition['tel'] = $tel;
        }
        if($status){
            $data['status'] = $status;
            $condition['status'] = $status;
        }


        if($name){
            $data['name'] = array('like','%'.$name.'%');
            $condition['name'] = $name;
        }
  //      $data['_complex'] = $map;

        if($this->user['sjquanxian']==1){
            $data['kaikaren'] = $this->user['id'];
        }

        //用户列表，是否需要新建列表D
        $totalsize =D('userinfo')->where($data)->count();
        $page  = $this->page($totalsize, 10);
        $lists = D('userinfo')->where($data)->relation(true)->order('createtime desc')->limit($page->firstRow . ',' . $page->listRows)->select();

        //2020.6.2 修改 添加的时候直接 显示添加的用户名 不用再次进行查询，
        //修正的sql语句为 update cmf_userinfo as uin SET uin.kaikarenname = ( select u.user_nicename from cmf_users u where u.id = uin.kaikaren )
//        foreach ($lists as $k => $v){
//             //$lists[$k]['kaikarenname'] = M('users')->where(array('id'=>$v['kaikaren']))->getField('user_nicename');
//            //'storetype=2 and cardnum='++$seldata
//            $seldata['cardnum'] = $v['cardnum'];
//            $kf = M('store')->where($seldata)->sum('storemoney');
////            print_r("kf:;"+$kf+"</br>");
//            dump($kf);
//        }

        $cardlevel = M('cardlevel')->where(array('status'=>1))->select();

        $this->assign('cardlevel',$cardlevel);
        $this->assign('condition',$condition);
        $this->assign('lists',$lists);
        $this->assign('page', $page->show());
        $this->assign('usid',$this->user['id']);
        $this->display();
    }

    public function del(){
        $cardnum = I('cardnum');
        if($cardnum){
            M('userinfo')->where(array('cardnum'=>$cardnum))->save(array('status'=>2));
            M('store')->where(array('cardnum'=>$cardnum))->save(array('temp1'=>'2'));
            $this->success('删除成功！');
        }else{
            $this->error('参数错误，无法删除!');
        }
    }

    public function changecardnum(){

        if(empty($_POST)){
            $cardnum = I('cardnum','','trim');

            $this->assign('cardnum',$cardnum);
            $this->display();
        }else{
            $cardnum = I('cardnum','','trim');
            $changednum = I('changednum','','trim');
            if($cardnum){
                if($changednum){

                    if(M('userinfo')->where(array('cardnum'=>$changednum))->count()!=0){//存在了不导入
                        $this->error('此卡号已注册，请更换卡号！');
                        return;
                    }

                    M('userinfo')->where(array('cardnum'=>$cardnum))->save(array('cardnum'=>$changednum));
                    M('store')->where(array('cardnum'=>$cardnum))->save(array('cardnum'=>$changednum));
                    $this->success('修改成功！',UU('Info/index'));
                }else{
                    $this->error('请输入更改后的卡号');
                }
            }else{
                $this->error('参数错误，无法更改!');
            }
        }
    }

    public function edit(){
        if(empty($_POST)){
        $cardnum = I('cardnum');
        $userInfo = D('userinfo')->where(array('cardnum'=>$cardnum))->find();
            if($userInfo){
                $cardlevel = M('cardlevel')->where(array('status'=>1))->select();
                $province = M('Region')->cache('province')->where(array('type'=>1))->select();
                if($userInfo['province']==0){
                    $userInfo['province']=17;
                }
                if($userInfo['city']==0){
                    $userInfo['city']=199;
                }
                if($userInfo['local']==0){
                    $userInfo['local']=199;
                }
                $city   = M('Region')->cache('city')->where(array('pid'=>$userInfo['province']))->select();
                $local = M('Region')->cache('local')->where(array('pid'=>$userInfo['city']))->select();
                $this->assign('city',$city);
                $this->assign('province', $province);
                $this->assign('local',$local);

                $this->assign('userinfo',$userInfo);
                $this->assign('cardlevel',$cardlevel);
                $this->display();
            }else{
                $this->error('卡号错误！');
            }
        }else{
            $cardnum = I('cardnum','','trim');
            $cardlevel = I('cardlevel');
            $name = I('name');
            $sex = I('sex');
            $tel = I('tel');
            $shenfenzheng = I('shenfenzheng');
            $shengri = I('shengri');
            $province = I('province');
            $city = I('city');
            $local = I('local');
            $address = I('address');
            $remark = I('remark');
            $extensiontime = I('extensiontime');
            $upgradetime = I('upgradetime');
            $yewuyuan = I('yewuyuan');
            $data = array(
                'name'      => $name,
                'sex'       => $sex,
                'tel'       => $tel,
                'cardlevel' => $cardlevel,
                'shenfenzheng' => $shenfenzheng,
                'shengri'   => $shengri,
                'province'  => $province,
                'city'      => $city,
                'local'     => $local,
                'address'   => $address,
                'yewuyuan'   => $yewuyuan,
                'remark'    => $remark
            );

            if($extensiontime){
                $data['extensiontime'] = $extensiontime;
            }
            if($upgradetime){
                $data['upgradetime'] = $upgradetime;
            }

            if(M('userinfo')->where(array('cardnum'=>$cardnum))->save($data)!==false){
                $this->success('保存成功！',UU('Info/index',array('cardnum'=>$cardnum)));
            }else{
                $this->error('保存失败');
            }
        }

    }

    public function add(){

        if(empty($_POST)){
            $province = M('Region')->cache('province')->where(array('type'=>1))->select();
            $city   = M('Region')->cache('city')->where(array('pid'=>17))->select();
            $local = M('Region')->cache('local')->where(array('pid'=>199))->select();
            $cardlevel = M('cardlevel')->where(array('status'=>1))->select();

            $this->assign('cardlevel',$cardlevel);
            $this->assign('province', $province);
            $this->assign('local',$local);
            $this->assign('city',$city);
            $this->display();
        }else{
            $cardnum = I('cardnum','','trim');
            $cardlevel = I('cardlevel');
            $name = I('name');
            $sex = I('sex');
            $tel = I('tel');
            $shenfenzheng = I('shenfenzheng');
            $shengri = I('shengri');
            $gudingdianhua = I('gudingdianhua');
            $totalstore = I('totalstore',0,'float');
            $paytype = I('paytype');
            $province = I('province');
            $city = I('city');
            $local = I('local');
            $address = I('address');
            $remark = I('remark');
            $yewuyuan = I('yewuyuan');

            if(M('userinfo')->where(array('cardnum'=>$cardnum))->count()!=0){
                $this->error('该会员卡号已存在！');
            }
            if(!$cardnum>0){
                $this->error('请正确输入会员卡号！');
            }

            $card = M('cardlevel')->where(array('id'=>$cardlevel))->find();
            $usedanwei = $card['usedanwei'];
            $usedtime = '';

            if($usedanwei == '-1'){
                $usedtime = '永久有效';
            }else if($usedanwei == 't'){
                $usedtime = date("Y-m-d",strtotime("+".$card['usetime']." day"));
            }else if($usedanwei == 'y'){
                $usedtime = date("Y-m-d",strtotime("+".$card['usetime']." month"));
            }else if($usedanwei == 'n'){
                $usedtime = date("Y-m-d",strtotime("+".$card['usetime']." year"));
            }

            $totalstore = $totalstore * 100;

            $data = array(
                'cardnum'   => $cardnum,
                'name'      => $name,
                'sex'       => $sex,
                'tel'       => $tel,
                'cardlevel' => $cardlevel,
                'shenfenzheng' => $shenfenzheng,
                'shengri'   => $shengri,
                'gudingdianhua' => $gudingdianhua,
                'province'  => $province,
                'city'      => $city,
                'local'     => $local,
                'address'   => $address,
                'remark'    => $remark,
                'paytype'   => $paytype,
                'kaikaren'  => $this->user['id'],
                'kaikarenname' => $this->user['user_nicename'],
                'totalstore'=> $totalstore,
                'usedstore' => $totalstore,
                'totalmenoy'=> $totalstore,
                'usedtime'  => $usedtime,
                'createtime'=>date('Y-m-d H:i:s'),
                'yewuyuan' => $yewuyuan
            );

            if(M('userinfo')->add($data)){
                $datas = array(
                    'cardnum'   => $cardnum,
                    'name'      => $name,
                    'laststore' => 0,
                    'remark'    => $remark,
                    'paytype'   => '初始储值',
                    'storetype' => 1,
                    'createby'  => $this->user['id'],
                    'createbyuser'=> $this->user['user_nicename'],
                    'nowstore'  => $totalstore,
                    'storemoney'=> $totalstore,
                    'storesendmoney'=> 0,
                    'createtime'=>date('Y-m-d H:i:s'),
                );

                M('store')->add($datas);

                $this->success('添加成功！',UU('Info/index'));
            }
        }
    }

    public function storehis(){
        $cardnum = I('cardnum');
        $name = I('name');
        $data = array('1'=>'1');
        $condition = array();

        if($name){
            $data['name'] = array('like','%'.$name.'%');
            $condition['name'] = $name;
        }

        if($cardnum){
            $data['cardnum'] = $cardnum;
            $condition['cardnum'] = $cardnum;
        }

        if($this->user['sjquanxian']==1){
            $data['createby'] = $this->user['id'];
        }

        $count = D('store')->where($data)->count();
        $page = $this->page($count,10);

        $hislist = D('store')->where($data)->order('id desc')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('hislist',$hislist);
        $this->assign('condition',$condition);
        $this->assign('page',$page->show());
        $this->assign('usid',$this->user['id']);
        $this->display();
    }


    public function exportstorehis(){
        //需要判断用户身份才可以进行导出数据
        if($this->user['id'] == 207 || $this->user['id'] == 210 ){

        }else{
            $this->error("你没有此权限");
        }
        $cardnum = I('cardnum_e');
        $name = I('name_e');
        $begintime = I('begintime');
        $endtime = I('endtime');

        $finalmap = array("temp1"=>1);

        $condition = array();

        if($begintime && $endtime) {
            $finalmap['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
        }

        if($name){
            $finalmap['name'] = array('like','%'.$name.'%');
            $condition['name'] = $name;
        }

        if($cardnum){
            $finalmap['cardnum'] = $cardnum;
            $condition['cardnum'] = $cardnum;
        }

        $filename = '会员消费历史列表_' . date('YmdHis') . '.csv';
        //设置不访问超时
        set_time_limit(0);
        $now = gmdate("D, d M Y H:i:s");

        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");

        $lists = D('store')->where($finalmap)->order('id desc')->select();

        $datas = array();
        foreach ($lists as $k => $v){
            $data = [
                $lists[$k]['cardnum'],
                $lists[$k]['name'],
                $lists[$k]['storetype']==1?'增加':'扣除',
                $lists[$k]['storemoney']/100,
                $lists[$k]['storesendmoney']/100,
                $lists[$k]['nowstore']/100,
                $lists[$k]['createtime'],
                $lists[$k]['createbyuser'],
                $lists[$k]['remark']
            ];
            $datas[] = $data;
        }
        $head=array('卡号','姓名','变动类型','变动金额','赠送金额','现有金额','操作时间','开卡人','备注');
        ob_start();

        $df = fopen("php://output", 'w');

        fputcsv($df,$head);
        foreach ($datas as $row) {
            fputcsv($df, $row);
        }
        fclose($df);

        echo ob_get_clean();
        unset($lists);
        unset($datas);
        die();
    }

    public function get_totalstore(){
        $id    = I('id', 0, 'int');
        $list   = M('cardlevel')->where(array('id'=>$id))->find();

        echo json_encode($list);

    }
}